package com.apps.realtyportal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import mapviewballoons.example.custom.CustomItemizedOverlay;
import mapviewballoons.example.custom.CustomOverlayItem;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.apps.essentials.AddTapLocationOverlay;
import com.apps.essentials.AddTapLocationOverlay2;
import com.apps.essentials.AddUserLocationOverlay;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.HomeActivity.Exchanger;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class LocationFragment extends SherlockListFragment {
	Context context;
	
	private MapFragment mMapFragment;
	private MyListFragment mMyListFragment;
	private Fragment mVisible = null;
	List listofaddress;
	/** An array of items to display in ArrayList */
	String lists_of_locations[] = new String[] { "Alcantara",
			"Alcoy",
			"Alegria",
			"Aloguinsan",
			"Argao",
			"Asturias",
			"Badian",
			"Balamban",
			"Bantayan",
			"Barili",
			"Bogo",
			"Boljoon",
			"Borbon",
			"Carcar",
			"Carmen",
			"Catmon",
			"Cebu City",
			"Compostela",
			"Consolacion",
			"Cordova",
			"Daanbantayan",
			"Dalaguete",
			"Danao City",
			"Dumanjug",
			"Ginatilan",
			"Lapu-Lapu City",
			"Liloan",
			"Madridejos",
			"Malabuyoc",
			"Mandaue City",
			"Medellin",
			"Minglanilla",
			"Moalboal",
			"Naga",
			"Oslob",
			"Pilar",
			"Pinamungahan",
			"Poro",
			"Ronda",
			"Samboan",
			"San Fernando",
			"San Francisco",
			"San Remigio",
			"Santa Fe",
			"Santander",
			"Sibonga",
			"Sogod",
			"Tabogon",
			"Tabuelan",
			"Talisay City",
			"Toledo City",
			"Tuburan",
			"Tudela" };
	//start here
	List<Overlay> newmapOverlays;
	AddUserLocationOverlay useroverlaylocation;
	OverlayItem overlayitem;
	MapController controlmap;
	ConsumeWebService cws;
	String centerAddress = ",Cebu,Philippines";
	final String KEY_ADDRESS = "address";
	final String KEY_LAT = "latitude";
	final String KEY_LON = "longitude";
	final String KEY_NAME = "property_name";
	final String KEY_DESCRIPTION = "property_description";
	final String KEY_PRICE = "price";
	final String KEY_TYPE = "propertyType";
	private ActionBar actionbar;
	Handler h;
	ArrayList listAdd = new ArrayList();
	AddTapLocationOverlay taplocation;
	CustomItemizedOverlay<CustomOverlayItem> newitemizedOverlay2;
	Drawable drawable;
	GeoPoint gp;
	double lat;
	double lon;
	String selected = null;
	Activity activity;
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		
		
		activity = getActivity();
		newmapOverlays = HomeActivity.Exchanger.mMapView.getOverlays();
		newmapOverlays.clear();
		HomeActivity.Exchanger.mMapView.setBuiltInZoomControls(true);
		controlmap = HomeActivity.Exchanger.mMapView.getController();
		//cws = new ConsumeWebService();
		//String dataws = cws.getAllProperty();
		//l = getListView()
		//String selectedLocation = l.getItemAtPosition(v.getId()).toString();
		// final ViewGroup parent = (ViewGroup) HomeActivity.Exchanger.mMapView
		// .getParent();
		// if (parent != null)
		// parent.removeView(HomeActivity.Exchanger.mMapView);

		
		selected = lists_of_locations[position].toString();
		AsyncTask tasksync;
		if (activity != null) {
			FragmentManager fm = getFragmentManager();
			
			//start here
	
			if(selected.compareTo("")==0)return;
			int numberOptions = 5;
			String []optionArray = new String[numberOptions];
			Geocoder gcoder = new Geocoder(getSherlockActivity());
			
			try{
				List<Address> results = gcoder.getFromLocationName(selected+centerAddress, numberOptions);
				Iterator<Address> locations = results.iterator();
				String raw = "\nRaw String:\n";
				String country;
				int opCount = 0;
				while(locations.hasNext()){
					Address location = locations.next();
					lat = location.getLatitude();
					lon = location.getLongitude();
					country = location.getCountryName();
					if(country == null) {
						country = "";
					} else {
						country =  ", "+country;
					}
					raw += location+"\n";
					optionArray[opCount] = location.getAddressLine(0)+", "+location.getAddressLine(1)
						+country+"\n";
					opCount ++;					
				}
				Log.i("Location-List", raw);
				Log.i("Location-List","\nOptions:\n");
				for(int i=0; i<opCount; i++){
					Log.i("Location-List","("+(i+1)+") "+optionArray[i]);
				}
				
			}catch(Exception ie){
				ie.printStackTrace();
				Log.e("Geocoder", "I/O Failure; is network available?",ie);
			}
			
			int userlat = (int)(lat*1E6);
			int userlon = (int)(lon*1E6);
			Toast.makeText(getSherlockActivity(), "lat "+userlat+"lon "+userlon, Toast.LENGTH_LONG).show();
			
			gp = new GeoPoint(userlat, userlon);
			drawable = getResources().getDrawable(R.drawable.mark_red);
			  newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, HomeActivity.Exchanger.mMapView);
			  CustomOverlayItem overlayItem3 = new CustomOverlayItem(gp, "Your Location", 
						"This is you", "","","","","","",
						"http://ia.media-imdb.com/images/M/MV5BMjAyNjk5Njk0MV5BMl5BanBnXkFtZTcwOTA4MjIyMQ@@._V1._SX40_CR0,0,40,54_.jpg");
				newitemizedOverlay2.addOverlay(overlayItem3);
				newmapOverlays.add(newitemizedOverlay2);
				newitemizedOverlay2.populateNow();
			controlmap.animateTo(gp);
			controlmap.setZoom(17);
			if (fm != null) {
				
				// Perform the FragmentTransaction to load in the list tab
				// content.;
				// Using FragmentTransaction#replace will destroy any Fragments
				// currently inside R.id.fragment_content and add the new
				// Fragment
				// in its place.
				// FragmentTransaction ft = fm.beginTransaction();
				// ft.replace(android.R.id.content, new MapFragment());
				// ft.commit();

				Fragment productDetailFragment = new MapFragment();
				FragmentTransaction transaction = getFragmentManager()
						.beginTransaction();
				transaction.addToBackStack(null);
				transaction
						.replace(android.R.id.content, productDetailFragment)
						.commit();
			}

			// Display a simple Toast to demonstrate that the click event is
			// working. Notice that Fragments have a
			// getString() method just like an Activity, so that you can quickly
			// access your localized Strings.
			
//			Toast.makeText(activity, "Position " +position +"  " + "tae"+selected, Toast.LENGTH_SHORT)
//					.show();
//			//new geoCodeSelectedLocation().execute(selected);
//			String selectedLocation = selected+centerAddress;
//	        if(selectedLocation.compareTo("")==0) return;
//	        int numberOptions = 5;
//	        String [] optionArray = new String[numberOptions];
//	        Geocoder gcoder = new Geocoder(activity);
//			//gecode address	
//			try{
//	            List<Address> results = gcoder.getFromLocationName(selectedLocation,numberOptions);
//	            Iterator<Address> locations = results.iterator();
//	            String raw = "\nRaw String:\n";
//	            String country;
//	            int opCount = 0;
//	            while(locations.hasNext()){
//	                Address location = locations.next();
//	                lat = (int)(location.getLatitude() * 1E6);
//	                lon = (int)(location.getLongitude() * 1E6);
//	                country = location.getCountryName();
//	                if(country == null) {
//	                    country = "";
//	                } else {
//	                    country =  ", "+country;
//	                }
//	                raw += location+"\n";
//	                optionArray[opCount] = location.getAddressLine(0)+", "+location.getAddressLine(1)+country+"\n";
//	                opCount ++;
//	            }
//	            Log.i("Location-List", raw);
//	            Log.i("Location-List","\nOptions:\n");
//	            for(int i=0; i<opCount; i++){
//	                Log.i("Location-List","("+(i+1)+") "+optionArray[i]);
//	            }
//						
//	        } catch (IOException e){
//	            Log.e("Geocoder", "I/O Failure; is network available?",e);
//	        }	
//	        gp = new GeoPoint(lat, lon);
//			overlayitem = new OverlayItem(gp, "Your Choosen Location", "This is you");
//			useroverlaylocation.addOverlay(overlayitem);		
////			newmapOverlays.clear();
//			newmapOverlays.add(useroverlaylocation);
		}

	}
	 
	public List getList(List list){
		listofaddress = list;
		return listofaddress;
	}
	private class geoCodeSelectedLocation extends AsyncTask<String, Void, List<Address>>{
		int numberOptions = 5;
		
		String [] optionArray = new String[numberOptions];
		@Override
		protected List<Address> doInBackground(String... selectedlocation) {
			String placeName = selected;
			// Break from execution if the user has not entered anything in the field
			Geocoder gcoder = new Geocoder(activity);
			
			// Note that the Geocoder uses synchronous network access, so in a serious application
			// it would be best to put it on a background thread to prevent blocking the main UI if network
			// access is slow. Here we are just giving an example of how to use it so, for simplicity, we
			// don't put it on a separate thread.
			
			List<Address> addresses = null;
			
			try {
				// Getting a maximum of 3 Address that matches the input text
				addresses = gcoder.getFromLocationName(placeName,numberOptions);
			} catch (IOException e) {
				e.printStackTrace();
			}			
			return addresses;
		}
		@Override
		protected void onPostExecute(List<Address> addresses) {
			// TODO Auto-generated method stub
//			if(addresses.equals("") || addresses.size()==0){
//				Toast.makeText(activity, "No Location found", Toast.LENGTH_SHORT).show();
//			}
//			Iterator<Address> locations = addresses.iterator();
//			String raw = "\nRaw String:\n";
//				String country;
//			int opCount = 0;
//			
//			while(locations.hasNext()){
//				Address location = locations.next();
//				lat = location.getLatitude();
//			lon = location.getLongitude();
//				country = location.getCountryName();
//				if(country == null) {
//					country = "";
//				} else {
//					country =  ", "+country;
//				}
//				raw += location+"\n";
//				optionArray[opCount] = location.getAddressLine(0)+", "+location.getAddressLine(1)
//					+country+"\n";
//			}
//			Log.i("Location-List", raw);
//			Log.i("Location-List","\nOptions:\n");
//			for(int i=0; i<opCount; i++){
//				Log.i("Location-List","("+(i+1)+") "+optionArray[i]);
//			}
//			int mdegreelat = (int) (lat * 1E6);
//			int mdegreelon = (int) (lon * 1E6);
//			
//			controlmap.animateTo(new GeoPoint(mdegreelat,mdegreelon));
			getList(addresses);
	}
}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// View view = inflater.inflate(R.layout.try_main, container, false);
		// ** Creating array adapter to set data in listview */
		// requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		//newitemizedOverlay2.removeAllBalloon();
		/** Creating array adapter to set data in listview */
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
				.getBaseContext(), android.R.layout.simple_list_item_1,
				lists_of_locations);

		/** Setting the array adapter to the listview */
		setListAdapter(adapter);

		return super.onCreateView(inflater, container, savedInstanceState);


	}

	@Override
	public void onStart() {
		super.onStart();
		// HomeActivity h = new HomeActivity();
		// actionbar = h.getSupportActionBar();
		// actionbar.setDisplayHomeAsUpEnabled(true);
		/** Setting the multiselect choice mode for the listview */
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

	}

	public void geoCodeAddress(){
		
	}

	/**
	 * This is our ListFragment class. You can put it in a separate java file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class MyListFragment extends SherlockListFragment {

		public static final String TAG = "listFragment";

		private final String[] mItems = { "List Item 1", "List Item 2",
				"List Item 3", "List Item 4", "List Item 5", "List Item 6",
				"List Item 7", "List Item 8", "List Item 9", "List Item 10" };

		public MyListFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// Inflate the ListView layout file.
			return inflater.inflate(R.layout.list_fragment, null);
		}

		@Override
		public void onViewCreated(View arg0, Bundle arg1) {
			super.onViewCreated(arg0, arg1);
			setListAdapter(new ArrayAdapter<String>(getSherlockActivity(),
					android.R.layout.simple_list_item_1, android.R.id.text1,
					mItems));
		}
	}

	/**
	 * This is the Fragment class that will hold the MapView as its content
	 * view. You can put it in a separate java file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class MapFragment extends SherlockFragment {

		public static final String TAG = "mapFragment";

		public MapFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// The Activity created the MapView for us, so we can do some init
			// stuff.
			// View v = inflater.inflate(R.layout.main, vg, false);

			final ViewGroup parent = (ViewGroup) HomeActivity.Exchanger.mMapView
					.getParent();

			if (parent != null)
				parent.removeView(HomeActivity.Exchanger.mMapView);

			HomeActivity.Exchanger.mMapView.setClickable(true);
			HomeActivity.Exchanger.mMapView.setBuiltInZoomControls(true); // If
																			// you
																			// want.

			return HomeActivity.Exchanger.mMapView;
		}
	}

}
